#!/usr/bin/env python
# coding: utf-8

# In[3]:


print('a'*30)
df = get_fundamentals(query(valuation))

# 以三阴三阳作为发现标的，如果是，保留后一日股价，以及后推30日股价，年底股价
def judge(span):
    indexes = span.index
    if (span.loc[indexes[0], 'close'] > span.loc[indexes[1], 'close'] > span.loc[indexes[2], 'close'] and 
        span.loc[indexes[5], 'close'] > span.loc[indexes[4], 'close'] > span.loc[indexes[3], 'close'] > span.loc[indexes[2], 'close']
        and span.loc[indexes[3], 'open'] < span.loc[indexes[4], 'open'] < span.loc[indexes[3], 'close'] and
        span.loc[indexes[4], 'open'] < span.loc[indexes[5], 'open'] < span.loc[indexes[4], 'close']):
        return True
    return False

print(df.shape)


# In[4]:


print(judge)
result = dict()

for index, row in df.iterrows():

    # 获取code过去2020～2021的行情
    prices = get_price(row['code'], start_date = '2020-01-01', end_date='2021-01-01')
    n = len(prices)

    result[str(row['code'])] = list()
    indexes = prices.index
    
    
    
    for i in range(n - 6):
        end = i+36 if i+36 < n else n-1
        start = i+6 if i+6 < n else n-1
        tmp = dict()

        if judge(prices[i:i+6]):
            tmp['start'] = str(indexes[i+6]) #起始日期
            tmp['nextday'] = 1 if prices.loc[indexes[start], 'open'] > prices.loc[indexes[i+5], 'close'] else 0
            tmp['n30days'] = prices.loc[indexes[end], 'close']
            tmp['profile'] = (prices.loc[indexes[end], 'close'] - prices.loc[indexes[start], 'open'])/prices.loc[indexes[end], 'close']
            result[str(row['code'])].append(tmp)
        print(' count ', len(result))
print(' result ', len(result))

import json
with open('result1.json', 'w', encoding='utf-8') as w:
    w.write(json.dumps(result, ensure_ascii=False, indent=4))


# In[6]:


# 统计次日上涨的概率
import matplotlib.pyplot as plt

total = []
for key, value in result.items():
    for item in value:
        total.append(item.get('nextday'))
    


# In[27]:


plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签

labels = ['次日上涨概率', '下跌概率']
print(total, Counter(total))
sizes = [sum(total), len(total)-sum(total)]
explode = (0.1,0)
plt.pie(sizes,explode=explode,labels=labels,autopct='%1.1f%%',shadow=False,startangle=150)
plt.title("红三兵次日涨跌分布")
plt.show()  


# In[13]:


# 收益率

margin = []
names = []
for key, value in result.items():
    for item in value:
        names.append(key)
        margin.append(item.get('profile'))
print(len(margin), margin)


# In[15]:


plt.bar(range(len(margin)), margin)
plt.title("红三兵次日买入持有30天的收益分布")
plt.show()


# In[29]:


## 计算平均收益
import numpy as np
print('平均收益', np.mean(margin))
print('最高收益', np.max(margin))
print('最低收益', np.min(margin))
print('中值收益', np.median(margin))
print('正收益期望', np.mean([item for item in margin if item>=0]))
print('负收益期望', np.mean([item for item in margin if item<0]))


# In[26]:


## 统计出现红三兵股票的次数
t = [len(value) for key, value in result.items()]
from collections import Counter
co = Counter(t)
print(co)
fig, ax=plt.subplots()
plt.bar(list(co.keys()), list(co.values()))
plt.title("红三兵出现次数分布")
#for x, y in enumerate(list(co.values())):
#    plt.text(x-0.2, y+50, "%s" %y)
# 取消边框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()





